/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DocumentCategorizationForm.java
 *
 * Created on 2010.30.3, 18:45:20
 */

package lv.rtu.ditf.dc.gui;

import java.awt.Color;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.swing.UIManager;

import lv.rtu.ditf.dc.document.DocumentVectorUtils;
import lv.rtu.ditf.dc.fs.CategoryFormatException;
import lv.rtu.ditf.dc.fs.DocumentCategory;
import lv.rtu.ditf.dc.fs.FileStorage;
import lv.rtu.ditf.dc.gui.listener.CategorizationDocumentListener;
import lv.rtu.ditf.dc.gui.listener.TestSetDocumentListener;
import lv.rtu.ditf.dc.thread.CategorizationCallback;
import lv.rtu.ditf.dc.thread.CategorizationThread;
import lv.rtu.ditf.dc.thread.CategorizationThreadRoutines;
import lv.rtu.ditf.dc.url.PlainTextPageLoader;
import lv.rtu.ditf.dc.url.UnsupportedContentTypeException;

/**
 * 
 * @author Pāvels Koliškins, Edgars Matisāns
 *
 */
public class DocumentCategorizationForm extends javax.swing.JFrame implements CategorizationCallback {
	private static final long serialVersionUID = -424284974406087615L;
	
	/** Creates new form DocumentCategorizationForm */
    public DocumentCategorizationForm() {
        initComponents();
        this.documentDataTextArea.getDocument().addDocumentListener(new TestSetDocumentListener(this));
        this.categorizeTextJTextArea.getDocument().addDocumentListener(new CategorizationDocumentListener(this));
 
        try {
            this.kNNJComboBox.removeAllItems();
            int kNNStartValue = FileStorage.get().getDocumentCategories().size() + 1;
            int kNNEndValue = Integer.MAX_VALUE;
            for (DocumentCategory documentCategory : FileStorage.get().getDocumentCategories()) {
                if (kNNEndValue > documentCategory.getDocuments().size()) {
                    kNNEndValue = documentCategory.getDocuments().size();
                }
            }

            for (int i = kNNStartValue; i <= kNNEndValue; i++) {
                this.kNNJComboBox.addItem(i);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jProgressBar1 = new javax.swing.JProgressBar();
        mainJTabbedPane = new javax.swing.JTabbedPane();
        testSetMainJPanel = new javax.swing.JPanel();
        errorJLabel = new javax.swing.JLabel();
        folderCreationJPanel = new javax.swing.JPanel();
        folderNameJLabel = new javax.swing.JLabel();
        categoryFolderNameJTextField = new javax.swing.JTextField();
        categoryCreationJButton = new javax.swing.JButton();
        testSetAddJPanel = new javax.swing.JPanel();
        testSetAddJScrollPane = new javax.swing.JScrollPane();
        documentDataTextArea = new javax.swing.JTextArea();
        resourceURLJLabel = new javax.swing.JLabel();
        resourceURLJTextField = new javax.swing.JTextField();
        getURLResourseDataJButton = new javax.swing.JButton();
        categoryNameJLabel = new javax.swing.JLabel();
        availableCategoriesJComboBox = new javax.swing.JComboBox();
        saveTextJButton = new javax.swing.JButton();
        dropTextJButton = new javax.swing.JButton();
        documentCategorizationJPanel = new javax.swing.JPanel();
        categorizationLoadResourceJPanel = new javax.swing.JPanel();
        categorizeResourceURLJLabel = new javax.swing.JLabel();
        categorizeLoadResourceJButton = new javax.swing.JButton();
        categorizeURLJTextField = new javax.swing.JTextField();
        categorizationTextAreaJScrollPane = new javax.swing.JScrollPane();
        categorizeTextJTextArea = new javax.swing.JTextArea();
        categorizeJButton = new javax.swing.JButton();
        kNNNeighbourJLabel = new javax.swing.JLabel();
        kNNJComboBox = new javax.swing.JComboBox();
        epsilonJLabel = new javax.swing.JLabel();
        epsilonJTextField = new javax.swing.JTextField();
        categorizationResultJPanel = new javax.swing.JPanel();
        categorizationResultJLabel = new javax.swing.JLabel();
        categorizeErrorJLabel = new javax.swing.JLabel();
        authorsJLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Dokumentu kategorizēšana");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
			public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        errorJLabel.setFont(new java.awt.Font("Tahoma", 1, 11));
        errorJLabel.setText("Apmācības dokumentu kopas konfigurēšana");

        folderCreationJPanel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));

        folderNameJLabel.setText("Mapes nosaukums:");

        categoryCreationJButton.setText("Pievienot");
        categoryCreationJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                categoryCreationJButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout folderCreationJPanelLayout = new org.jdesktop.layout.GroupLayout(folderCreationJPanel);
        folderCreationJPanel.setLayout(folderCreationJPanelLayout);
        folderCreationJPanelLayout.setHorizontalGroup(
            folderCreationJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(folderCreationJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(folderCreationJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(folderCreationJPanelLayout.createSequentialGroup()
                        .add(folderNameJLabel)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(categoryFolderNameJTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 348, Short.MAX_VALUE))
                    .add(categoryCreationJButton))
                .addContainerGap())
        );
        folderCreationJPanelLayout.setVerticalGroup(
            folderCreationJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(folderCreationJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(folderCreationJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(folderNameJLabel)
                    .add(categoryFolderNameJTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(categoryCreationJButton)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        testSetAddJPanel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));

        documentDataTextArea.setColumns(20);
        documentDataTextArea.setFont(new java.awt.Font("Times New Roman", 0, 9));
        documentDataTextArea.setRows(5);
        testSetAddJScrollPane.setViewportView(documentDataTextArea);

        resourceURLJLabel.setText("Dokumenta saite:");

        getURLResourseDataJButton.setText("Ielādēt");
        getURLResourseDataJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                getURLResourseDataJButtonActionPerformed(evt);
            }
        });

        categoryNameJLabel.setText("Kategorija:");

        availableCategoriesJComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                availableCategoriesJComboBoxItemStateChanged(evt);
            }
        });

        saveTextJButton.setText("Saglabāt");
        saveTextJButton.setEnabled(false);
        saveTextJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveTextJButtonActionPerformed(evt);
            }
        });

        dropTextJButton.setText("Dzēst");
        dropTextJButton.setEnabled(false);
        dropTextJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dropTextJButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout testSetAddJPanelLayout = new org.jdesktop.layout.GroupLayout(testSetAddJPanel);
        testSetAddJPanel.setLayout(testSetAddJPanelLayout);
        testSetAddJPanelLayout.setHorizontalGroup(
            testSetAddJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, testSetAddJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(testSetAddJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, testSetAddJScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE)
                    .add(testSetAddJPanelLayout.createSequentialGroup()
                        .add(testSetAddJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(resourceURLJLabel)
                            .add(categoryNameJLabel))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(testSetAddJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(testSetAddJPanelLayout.createSequentialGroup()
                                .add(resourceURLJTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 201, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(getURLResourseDataJButton))
                            .add(availableCategoriesJComboBox, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(testSetAddJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(dropTextJButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE)
                            .add(saveTextJButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        testSetAddJPanelLayout.setVerticalGroup(
            testSetAddJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(testSetAddJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(testSetAddJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(categoryNameJLabel)
                    .add(availableCategoriesJComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(dropTextJButton))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(testSetAddJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(resourceURLJLabel)
                    .add(resourceURLJTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 22, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(saveTextJButton)
                    .add(getURLResourseDataJButton))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(testSetAddJScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                .addContainerGap())
        );

        org.jdesktop.layout.GroupLayout testSetMainJPanelLayout = new org.jdesktop.layout.GroupLayout(testSetMainJPanel);
        testSetMainJPanel.setLayout(testSetMainJPanelLayout);
        testSetMainJPanelLayout.setHorizontalGroup(
            testSetMainJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, testSetMainJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(testSetMainJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, testSetAddJPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(errorJLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 465, Short.MAX_VALUE)
                    .add(folderCreationJPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        testSetMainJPanelLayout.setVerticalGroup(
            testSetMainJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(testSetMainJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(errorJLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(folderCreationJPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(testSetAddJPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        mainJTabbedPane.addTab("Apmācības kopa", testSetMainJPanel);

        categorizationLoadResourceJPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        categorizeResourceURLJLabel.setText("Dokumenta saite:");

        categorizeLoadResourceJButton.setText("Ielādēt");
        categorizeLoadResourceJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                categorizeLoadResourceJButtonActionPerformed(evt);
            }
        });

        categorizeTextJTextArea.setColumns(20);
        categorizeTextJTextArea.setRows(5);
        categorizationTextAreaJScrollPane.setViewportView(categorizeTextJTextArea);

        categorizeJButton.setText("Kategorizēt");
        categorizeJButton.setEnabled(false);
        categorizeJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                categorizeJButtonActionPerformed(evt);
            }
        });

        kNNNeighbourJLabel.setText("kNN parametrs:");

        epsilonJLabel.setText("Epsilon:");

        epsilonJTextField.setText("0.1");

        org.jdesktop.layout.GroupLayout categorizationLoadResourceJPanelLayout = new org.jdesktop.layout.GroupLayout(categorizationLoadResourceJPanel);
        categorizationLoadResourceJPanel.setLayout(categorizationLoadResourceJPanelLayout);
        categorizationLoadResourceJPanelLayout.setHorizontalGroup(
            categorizationLoadResourceJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, categorizationLoadResourceJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(categorizationLoadResourceJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(categorizationTextAreaJScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE)
                    .add(categorizationLoadResourceJPanelLayout.createSequentialGroup()
                        .add(categorizationLoadResourceJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(categorizeResourceURLJLabel)
                            .add(kNNNeighbourJLabel))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(categorizationLoadResourceJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(categorizeURLJTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE)
                            .add(categorizationLoadResourceJPanelLayout.createSequentialGroup()
                                .add(kNNJComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 63, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(epsilonJLabel)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(epsilonJTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(categorizationLoadResourceJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(categorizeJButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(categorizeLoadResourceJButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE))))
                .addContainerGap())
        );
        categorizationLoadResourceJPanelLayout.setVerticalGroup(
            categorizationLoadResourceJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(categorizationLoadResourceJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(categorizationLoadResourceJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(categorizeResourceURLJLabel)
                    .add(categorizeURLJTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(categorizeLoadResourceJButton))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(categorizationLoadResourceJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(categorizeJButton)
                    .add(kNNNeighbourJLabel)
                    .add(kNNJComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(epsilonJLabel)
                    .add(epsilonJTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 22, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(categorizationTextAreaJScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE)
                .addContainerGap())
        );

        categorizationResultJPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        categorizationResultJLabel.setText("Kategorizēšanas rezultāti pagaidām nav zināmi.");
        categorizationResultJLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        categorizationResultJLabel.setVerticalTextPosition(javax.swing.SwingConstants.TOP);

        org.jdesktop.layout.GroupLayout categorizationResultJPanelLayout = new org.jdesktop.layout.GroupLayout(categorizationResultJPanel);
        categorizationResultJPanel.setLayout(categorizationResultJPanelLayout);
        categorizationResultJPanelLayout.setHorizontalGroup(
            categorizationResultJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(categorizationResultJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(categorizationResultJLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 431, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(22, Short.MAX_VALUE))
        );
        categorizationResultJPanelLayout.setVerticalGroup(
            categorizationResultJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(categorizationResultJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(categorizationResultJLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 85, Short.MAX_VALUE)
                .addContainerGap())
        );

        categorizeErrorJLabel.setFont(new java.awt.Font("Tahoma", 1, 11));
        categorizeErrorJLabel.setText("Dokumentu kategorizēšana");

        authorsJLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        authorsJLabel.setText("P. Koliškins, E. Matisāns");

        org.jdesktop.layout.GroupLayout documentCategorizationJPanelLayout = new org.jdesktop.layout.GroupLayout(documentCategorizationJPanel);
        documentCategorizationJPanel.setLayout(documentCategorizationJPanelLayout);
        documentCategorizationJPanelLayout.setHorizontalGroup(
            documentCategorizationJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(documentCategorizationJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(documentCategorizationJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, categorizationLoadResourceJPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, categorizationResultJPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(documentCategorizationJPanelLayout.createSequentialGroup()
                        .add(categorizeErrorJLabel)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 177, Short.MAX_VALUE)
                        .add(authorsJLabel)))
                .addContainerGap())
        );
        documentCategorizationJPanelLayout.setVerticalGroup(
            documentCategorizationJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(documentCategorizationJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(documentCategorizationJPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(categorizeErrorJLabel)
                    .add(authorsJLabel))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(categorizationLoadResourceJPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(categorizationResultJPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        mainJTabbedPane.addTab("Kategorizēšana", documentCategorizationJPanel);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(mainJTabbedPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 490, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(mainJTabbedPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                .addContainerGap())
        );

        mainJTabbedPane.getAccessibleContext().setAccessibleName("Apmācības kopa");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public void setErrorMsg(String errorMsg) {
        this.errorJLabel.setText(errorMsg);
        this.errorJLabel.setForeground(Color.RED);
    }

    public void setMsg(String msg) {
        this.errorJLabel.setText(msg);
        this.errorJLabel.setForeground(Color.BLACK);
    }

    public void setCategorizeErrorMsg(String errorMsg) {
        this.categorizeErrorJLabel.setText(errorMsg);
        this.categorizeErrorJLabel.setForeground(Color.RED);
    }

    public void setCategorizeMsg(String msg) {
        this.categorizeErrorJLabel.setText(msg);
        this.categorizeErrorJLabel.setForeground(Color.BLACK);
    }
    
	
    /**
	 * Prints result of categorization to the user.
	 * @param categorizationResult Map containing percents for each category
	 * @param executioTime time when categorization process finished
	 */
    @Override
	public void onCategorizationComplete(Map<String, Double> categorizationResult, long executionTime) {
        lockCategorizationArea(false);
        if (categorizationResult == null) {
        	setCategorizeErrorMsg("Kļūda, kategorizējot dokumentu!");
        	return;
        }
        
        setCategorizeMsg("Dokumentu kategorizēšana ir pabeigta!");
        this.categorizationResultJLabel.setText("");
        if (categorizationResult.size() == 0) {
            StringBuffer sb = new StringBuffer();
            sb.append("<HTML>");
            sb.append("Diemžēl dokumentu nevar attiecināt pie kādas kategorijas! <br /><br />");
            sb.append("Kategorizēšanai bija nepieciešamas " + (executionTime / 1000) + " sekundes!<br />");
            sb.append("Lūdzu mēģiniet kategorizēt citu dokumentu! <br /><br />");
            sb.append("Paldies!");
            sb.append("</HTML>");
            this.categorizationResultJLabel.setText(sb.toString());
         }
        else {
            StringBuffer sb = new StringBuffer();
            sb.append("<HTML>");
        	
        	//due to precision loss, make sure in sum there are 100%
            int percents = 0;
            for (String categoryName : categorizationResult.keySet()) {
                percents += (int) (categorizationResult.get(categoryName) * 100);
            }
            int percentsToAdd = 100 - percents;
            
            //print percents
            boolean wasFirstRecordRead = false;
            for (String categoryName : categorizationResult.keySet()) {
                if (!wasFirstRecordRead) {
                    sb.append("Dokuments pieder pie kategorijas - " + categoryName.toUpperCase() + "!<br />");
                    sb.append("Kategorizēšanai bija nepieciešamas " + (executionTime / 1000) + " sekundes!<br />");
                    sb.append("---------------------------------------------------------------------<br />");
                    wasFirstRecordRead = true;
                    
                    sb.append(categoryName + " - " + ((int)	(categorizationResult.get(categoryName) * 100) + percentsToAdd) + " % <br />");
                } else {
                    sb.append(categoryName + " - " + (int) (categorizationResult.get(categoryName) * 100) + " % <br />");
                }
            }

            sb.append("</HTML>");
            this.categorizationResultJLabel.setText(sb.toString());
        }
	}
	
    public void lockCategorizationArea(boolean lock) {

        if (lock) {
            this.categorizeLoadResourceJButton.setEnabled(false);
            this.categorizeURLJTextField.setEnabled(false);
            this.categorizeJButton.setEnabled(false);
            this.categorizeTextJTextArea.setEnabled(false);
            this.kNNJComboBox.setEnabled(false);
        } else {
            this.categorizeLoadResourceJButton.setEnabled(true);
            this.categorizeURLJTextField.setEnabled(true);
            this.categorizeJButton.setEnabled(true);
            this.categorizeTextJTextArea.setEnabled(true);
            this.kNNJComboBox.setEnabled(true);
        }
    }

    private void restoreDropDownBoxContents() throws IOException {
        FileStorage fileStorage = FileStorage.get();

        this.availableCategoriesJComboBox.removeAllItems();
        this.availableCategoriesJComboBox.addItem("Lūdzu izvēlaties kategoriju");
        for (DocumentCategory documentCategoryItem : fileStorage.getDocumentCategories()) {
            this.availableCategoriesJComboBox.addItem(documentCategoryItem.getName());
        }
    }

    public void lockSaveButton(boolean lock) {
        
        if (lock) this.saveTextJButton.setEnabled(false);
        else this.saveTextJButton.setEnabled(true);
    }

    public void lockCategorizeButton(boolean lock) {

        if (lock) this.categorizeJButton.setEnabled(false);
        else this.categorizeJButton.setEnabled(true);
    }
    
    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened

        try {
            restoreDropDownBoxContents();
        } catch (IOException ex) {
            setErrorMsg("Kļūda, nolasot mapes no diska!");
        }
    }//GEN-LAST:event_formWindowOpened

    private void categoryCreationJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_categoryCreationJButtonActionPerformed
        FileStorage fileStorage = FileStorage.get();
        if (this.categoryFolderNameJTextField.getText() != null &&
                !this.categoryFolderNameJTextField.getText().trim().equalsIgnoreCase("")) {
            try {
                fileStorage.createDocumentCategory(this.categoryFolderNameJTextField.getText());
                
                restoreDropDownBoxContents();

                this.categoryFolderNameJTextField.setText("");
            } catch (IOException ex) {
                setErrorMsg("Kļūda, pievienojot jaunu direktoriju");
                ex.printStackTrace();
            } catch (CategoryFormatException e) {
                setErrorMsg("Direktorijas nosaukums var saturēt tikai latiņu alfabēta simbolus");
            }
        } else {
            setErrorMsg("Jūs neesat ievadījuši informāciju!");
        }

}//GEN-LAST:event_categoryCreationJButtonActionPerformed

    private void availableCategoriesJComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_availableCategoriesJComboBoxItemStateChanged
        String selectedItem = (String) evt.getItem();
        if (!selectedItem.equalsIgnoreCase("Lūdzu izvēlaties kategoriju")) {
            try {
                FileStorage fileStorage = FileStorage.get();
                int filesAvailable = fileStorage.getDocumentCategory(selectedItem).getDocuments().size();
                if (filesAvailable == 1) {
                    setMsg("Šajā kategorijā ir 1 fails!");
                } else {
                    setMsg("Šajā kategorijā ir " + filesAvailable + " faili!");
                }
            } catch (Exception ex) {
                setErrorMsg("Kļūda, apskatot kategoriju!");
            }
            this.dropTextJButton.setEnabled(true);
        } else {
            setMsg("Apmācības dokumentu kopas konfigurēšana");
            this.dropTextJButton.setEnabled(false);
        }
    }//GEN-LAST:event_availableCategoriesJComboBoxItemStateChanged

    private void getURLResourseDataJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_getURLResourseDataJButtonActionPerformed

        try {
            this.documentDataTextArea.setText(PlainTextPageLoader.loadPage(this.resourceURLJTextField.getText()));
        } catch (IOException iOException) {
            this.setErrorMsg("Kļūda, lejupielādējot datus!");
            iOException.printStackTrace();
        } catch (UnsupportedContentTypeException contentTypeException) {
            this.setErrorMsg("Kļūda, lejupielādējot datus!");
            contentTypeException.printStackTrace();
        }

    }//GEN-LAST:event_getURLResourseDataJButtonActionPerformed

    private void dropTextJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dropTextJButtonActionPerformed
        String selectedCategory = (String) this.availableCategoriesJComboBox.getSelectedItem();
        if (!selectedCategory.equalsIgnoreCase("Lūdzu izvēlaties kategoriju")) {
            FileStorage fileStorage = FileStorage.get();
            try {
                DocumentCategory documentCategory = fileStorage.getDocumentCategory(selectedCategory);
                if (fileStorage.deleteDirectory(documentCategory)) {

                    restoreDropDownBoxContents();
                    
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            
        }
    }//GEN-LAST:event_dropTextJButtonActionPerformed

    private void saveTextJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveTextJButtonActionPerformed
        String selectedCategory = (String) this.availableCategoriesJComboBox.getSelectedItem();
        if (!selectedCategory.equalsIgnoreCase("Lūdzu izvēlaties kategoriju")) {

            try {
                FileStorage fileStorage = FileStorage.get();
                DocumentCategory documentCategory = fileStorage.getDocumentCategory(selectedCategory);

                documentCategory.addDocument(this.documentDataTextArea.getText().trim());

                restoreDropDownBoxContents();
                this.documentDataTextArea.setText("");
                this.resourceURLJTextField.setText("");

                documentCategory.buildIndexes();
            } catch (Exception ex) {
                setErrorMsg("Kļūda, saglabājot datus!");
            }

        } else {
            setErrorMsg("Lūdzu, izvēlaties kategoriju!");
        }
    }//GEN-LAST:event_saveTextJButtonActionPerformed

    private void categorizeLoadResourceJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_categorizeLoadResourceJButtonActionPerformed
        try {
            this.categorizeTextJTextArea.setText(PlainTextPageLoader.loadPage(this.categorizeURLJTextField.getText()));
            this.setCategorizeMsg("Dokumentu kategorizēšana");
        } catch (IOException iOException) {
            this.setCategorizeErrorMsg("Kļūda, lejupielādējot datus!");
            iOException.printStackTrace();
        } catch (UnsupportedContentTypeException contentTypeException) {
            this.setCategorizeErrorMsg("Kļūda, lejupielādējot datus!");
            contentTypeException.printStackTrace();
        }
    }//GEN-LAST:event_categorizeLoadResourceJButtonActionPerformed

    private void categorizeJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_categorizeJButtonActionPerformed
        HashMap<String, Integer> testDocumentVector = DocumentVectorUtils.getDocumentVector(this.categorizeTextJTextArea.getText().trim());

        
        boolean epsilonError = false; double epsilon = 0.0;
        try {
            epsilon = Double.valueOf(this.epsilonJTextField.getText()).doubleValue();
        } catch (Exception ex) {
            this.setCategorizeErrorMsg("Epsilon vērtībai jābūt robežās no 0 līdz 1");
            epsilonError = true;
        }
        if (!(epsilon >= 0.0 && epsilon <= 1.0)) {
            this.setCategorizeErrorMsg("Epsilon vērtībai jābūt robežās no 0 līdz 1");
            epsilonError = true;
        }
         
        if (!epsilonError) {
            //get thread
            CategorizationThread categorizationThread = CategorizationThreadRoutines.categorizationThread;
            if (categorizationThread == null || !categorizationThread.isAlive()) {
                //create new thread
                this.lockCategorizationArea(true);
                this.setCategorizeMsg("Izvēlētais dokuments tiek kategorizēts!");

                categorizationThread = new CategorizationThread(testDocumentVector, ((Integer) this.kNNJComboBox.getSelectedItem()).intValue(), epsilon);
                categorizationThread.addCategorizationListener(this);
                categorizationThread.start();
            } else {
                //error thread is alive
                this.setCategorizeErrorMsg("Pašreiz notiek dokumentu kategorizēšana!");
            }
        }

    }//GEN-LAST:event_categorizeJButtonActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        try {   
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    	
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new DocumentCategorizationForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel authorsJLabel;
    private javax.swing.JComboBox availableCategoriesJComboBox;
    private javax.swing.JPanel categorizationLoadResourceJPanel;
    private javax.swing.JLabel categorizationResultJLabel;
    private javax.swing.JPanel categorizationResultJPanel;
    private javax.swing.JScrollPane categorizationTextAreaJScrollPane;
    private javax.swing.JLabel categorizeErrorJLabel;
    private javax.swing.JButton categorizeJButton;
    private javax.swing.JButton categorizeLoadResourceJButton;
    private javax.swing.JLabel categorizeResourceURLJLabel;
    private javax.swing.JTextArea categorizeTextJTextArea;
    private javax.swing.JTextField categorizeURLJTextField;
    private javax.swing.JButton categoryCreationJButton;
    private javax.swing.JTextField categoryFolderNameJTextField;
    private javax.swing.JLabel categoryNameJLabel;
    private javax.swing.JPanel documentCategorizationJPanel;
    private javax.swing.JTextArea documentDataTextArea;
    private javax.swing.JButton dropTextJButton;
    private javax.swing.JLabel epsilonJLabel;
    private javax.swing.JTextField epsilonJTextField;
    private javax.swing.JLabel errorJLabel;
    private javax.swing.JPanel folderCreationJPanel;
    private javax.swing.JLabel folderNameJLabel;
    private javax.swing.JButton getURLResourseDataJButton;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JComboBox kNNJComboBox;
    private javax.swing.JLabel kNNNeighbourJLabel;
    private javax.swing.JTabbedPane mainJTabbedPane;
    private javax.swing.JLabel resourceURLJLabel;
    private javax.swing.JTextField resourceURLJTextField;
    private javax.swing.JButton saveTextJButton;
    private javax.swing.JPanel testSetAddJPanel;
    private javax.swing.JScrollPane testSetAddJScrollPane;
    private javax.swing.JPanel testSetMainJPanel;
    // End of variables declaration//GEN-END:variables
}
